package sg.edu.nus.dbd.action;

import java.sql.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import sg.edu.nus.dbd.biz.DashboardBiz;
import sg.edu.nus.dbd.biz.ConfigurationBiz;
import sg.edu.nus.dbd.formbean.DetailParamData;
import sg.edu.nus.dbd.formbean.ThresholdConfig;
import sg.edu.nus.dbd.util.Constants;
import sg.edu.nus.dbd.util.DateUtil;
import sg.edu.nus.dbd.util.MyLogger;

public class ThirdBreakdownAction extends BaseAction {

	public ActionForward performAction(ActionMapping mapping, ActionForm form,
			HttpServletRequest req, HttpServletResponse res) throws Exception {
		try {
			MyLogger.debug(this.getClass(), "execute::Start...");
			HttpSession session = req.getSession(false);
			String currentParam = (String) session
					.getAttribute("CurrentParameter");

			String indexParam = (String) req.getParameter("pIndex");

			int selectedIndex = -1;
			try {
				selectedIndex = Integer.parseInt(indexParam);
			} catch (Exception e) {
				e.printStackTrace();
				// ignore
			}

			Date startDate = null;
			Date endDate = null;

			try {
				List<DetailParamData> level2DataList = (List<DetailParamData>) session
						.getAttribute("level2DataList");
				DetailParamData selectedData = level2DataList
						.get(selectedIndex);
				if (selectedData != null) {
					startDate = selectedData.getStartDate();
					endDate = selectedData.getEndDate();
				}
			} catch (Exception e) {
				e.printStackTrace();
				// ignore
			}
			List<DetailParamData> level3DataList = null;

			// If user provides a valid selection, the start date and end date
			// will not be null
			if (startDate != null && endDate != null) {
				level3DataList = new DashboardBiz().getLevel3Statistics(
						currentParam, DateUtil.addMinuteToDate(startDate, -60),
						endDate);
			}

			ThresholdConfig thConfig = new ConfigurationBiz()
					.getThresholdParameter(currentParam);
            System.out.println(thConfig);
			req.setAttribute("warningLevel", thConfig.getWarningLevel());
			req.setAttribute("criticalLevel", thConfig.getCriticalLevel());
			req.setAttribute("inverse", Constants.DASHBOARD_PARAMS_INVERSE
					.get(currentParam));
			req.setAttribute("startDate", DateUtil.getDateString(startDate));
			req.setAttribute("endDate", DateUtil.getDateString(endDate));
			req.setAttribute("level3DataList", level3DataList);

			return mapping.findForward("success");

		} catch (Exception e) {
			MyLogger.error(this.getClass(), e);
			return mapping.findForward("error");
		}
	}
}
